{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**泛函连接理论求解PDG问题**\n",
    "> 思路"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "import torch\n",
    "import torch.nn.functional as F\n",
    "import torch.nn as nn\n",
    "\n",
    "# 切比雪夫多项式拟合函数\n",
    "def chebyshev_t(n, x):\n",
    "    if n == 0:\n",
    "        return torch.ones_like(x)\n",
    "    elif n == 1:\n",
    "        return x\n",
    "    else:\n",
    "        return 2 * x * chebyshev_t(n - 1, x) - chebyshev_t(n - 2, x)\n",
    "\n",
    "def chebyshev_derivative(n, x):\n",
    "    # Requires grad to use autograd\n",
    "    if not x.requires_grad:\n",
    "        x.requires_grad_(True)\n",
    "    \n",
    "    # Get Chebyshev polynomial value\n",
    "    y = chebyshev_t(n, x)\n",
    "    print(y.size())\n",
    "    # Calculate derivative\n",
    "    derivative = torch.autograd.grad(y.sum(), x, create_graph=True)[0]\n",
    "    \n",
    "    return derivative\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([])\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor(-2.8800, grad_fn=<AddBackward0>)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chebyshev_derivative(3,torch.tensor(0.1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
